package router

/*****************************
1.功能：ftp接收数据服务
2.协议：ftp
3.作者：汪君军
4.日期：2022-06-23
******************************/
import (
	"flag"
	"github.com/fclairamb/ftpserver/config"
	ftpserver "github.com/fclairamb/ftpserverlib"
	"github.com/fclairamb/go-log/gokit"
	"github.com/sirupsen/logrus"
	"io/ioutil"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/fclairamb/ftpserver/server"
)

// 定义接口
type Router interface {
	CreateFtpRouter(fileName string)
}
type router struct {
}

func NewRouter() *router {
	return &router{}
}

var (
	ftpServer *ftpserver.FtpServer
	driver    *server.Server
)

func stop() {
	driver.Stop()
	if err := ftpServer.Stop(); err != nil {
		logrus.Error("Problem stopping server", "err", err)
	}
}
func signalHandler() {
	ch := make(chan os.Signal, 1)
	signal.Notify(ch, syscall.SIGTERM)
	sig := <-ch
	if sig == syscall.SIGTERM {
		stop()
	}
}

// 创建ftp网关服务端
func (r *router) CreateFtpRouter(fileName string) {

	flagSet := flag.NewFlagSet("ftpserver", flag.ExitOnError)
	confFile := flagSet.String("conf", "", "Configuration file")
	onlyConf := flagSet.Bool("conf-only", false, "Only create the conf")
	flagSet.Parse(os.Args[1:])

	logger := gokit.New().With(
		"ts", gokit.GKDefaultTimestampUTC,
		"caller", gokit.GKDefaultCaller,
	)
	autoCreate := *onlyConf

	if *confFile == "" {
		*confFile = fileName
		autoCreate = true
	}

	if autoCreate {
		if _, err := os.Stat(*confFile); os.IsNotExist(err) {
			logrus.Info("No conf file, creating one", "confFile", *confFile)
			if err := ioutil.WriteFile(*confFile, confFileContent(*confFile), 0600); err != nil {
				logrus.Warn("Couldn't create conf file", "confFile", *confFile)
			}
		}
	}

	conf, err := config.NewConfig(*confFile, logger)
	if err != nil {
		logrus.Warn("Can't load conf", "err", err)
		return
	}

	driver, err := server.NewServer(conf, logger.With("component", "driver"))
	if err != nil {
		logrus.Error("Could not load the driver", "err", err)
		return
	}

	ftpServer := ftpserver.NewFtpServer(driver)
	ftpServer.Logger = logger.With("component", "server")

	go signalHandler()

	if *onlyConf {
		logrus.Warn("Only creating conf")
		return
	}

	if err := ftpServer.ListenAndServe(); err != nil {
		logrus.Error("Problem listening", "err", err)
	}

	if err := driver.WaitGracefully(time.Minute); err != nil {
		logrus.Warn("Problem stopping server", "err", err)
	}
}

func confFileContent(fileName string) []byte {
	//创建byte 数组来存储文件
	fileContext, err := ioutil.ReadFile(fileName)
	if err != nil {
		logrus.Info("读取文件报错")
		return nil
	}
	return fileContext
}
